<?php 
class Am_Paysystem_Moip extends Am_Paysystem_CreditCard
{
    const PLUGIN_STATUS = self::STATUS_BETA;
    const PLUGIN_DATE = '$Date$';
    const PLUGIN_REVISION = '4.2.13.4d4e034';
    
    const TOKEN = 'moip_token';

    // First step urls
    const XML_TEST_URL = 'https://desenvolvedor.moip.com.br/sandbox/ws/alpha/EnviarInstrucao/Unica';
    const XML_URL = 'https://www.moip.com.br/ws/alpha/EnviarInstrucao/Unica';
    // Second step urls
    const JSON_TEST_URL = 'https://desenvolvedor.moip.com.br/sandbox/transparente/MoipWidget-v2.js';
    const JSON_URL = 'https://www.moip.com.br/transparente/MoipWidget-v2.js'; 
         
    protected $defaultTitle = 'Moip payment';
    protected $defaultDescription = 'accepts all major credit cards';
    
    public function getSupportedCurrencies()
    {
        return array('USD', 'EUR', 'BRA');
    }   

    public function _doBill(Invoice $invoice, $doFirst, CcRecord $cc, Am_Paysytem_Result $result)
    {xdebug_break();
        
        $token = $invoice->getUser()->data()->get(self::TOKEN);
        if(!$token)
            return $result->setErrorMessages(array(__('Payment failed')));
        
        if($doFirst && (doubleval($invoice->first_total) <= 0))
        {
            $tr = new Am_Paysystem_Transaction_Free($this);
            $tr->process();
            $result->setSuccess($tr);   
        } else {
            $tr = new Am_Paysystem_Transaction_Moip($this, $invoice, $doFirst);
            $tr->run($result);
        }        
    }
    
    public function getCreditCardTypeOptions()
    {
        return array('visa' => 'Visa', 'mastercard' => 'MasterCard');
    }
    public function getFormOptions()
    {
        return array_merge(parent::getFormOptions(), array(self::CC_CODE));
    }
    
    public function storeCreditCard(CcRecord $cc, Am_Paysytem_Result $result)
    {
        return parent::storeCreditCard($cc, $result);
    }
    
    public function loadCreditCard(Invoice $invoice)
    {
        return parent::loadCreditCard($invoice);
    }
    
 
    function init()
    {
        parent::init();

        require_once dirname(__FILE__).'/libs/moip_lib.php';
        require_once dirname(__FILE__).'/libs/moip_client_lib.php';
        require_once dirname(__FILE__).'/libs/moip_form.php';

//        $this->getDi()->userTable->customFields()->add(new Am_CustomFieldText('moip_complemento', 'Complemento'));
//        $this->getDi()->userTable->customFields()->add(new Am_CustomFieldText('moip_numero', 'Numero'));
//        $this->getDi()->userTable->customFields()->add(new Am_CustomFieldText('moip_neighborhood', 'Bairro'));
    }
   
    public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result)
    {      
        parent::_process($invoice, $request, $result);
        
        $user = $invoice->getUser();
        $moip = new Moip();
        
        $test_environment = $this->getConfig('testing') ? 'test' : null;
        $moip->setEnviroment($test_environment);
        $moip->setCredential(array('key' => $this->getConfig('key'), 'token' => $this->getConfig('token')));
        
        $moip->setUniqueID($invoice->public_id);
        $moip->setValue($invoice->first_total);
        $moip->setReason('MoIP plugin for aMember');
        
        $moip->setPayer(array(
                'name' => $user->name_f." ".$user->name_l,
                'email' => $user->email,
                'payerId' => $user->user_id,
                'billingAddress' => array(
                        'address' => $user->street,
                        'number' => $user->street,
                        'complement' => $user->street,
                        'city' => $user->city,
                        'neighborhood' => $user->street,
                        'state' => $user->state,
                        'country' => $user->country,
                        'zipCode' => $user->zip,
                        'phone' => $user->phone
                        ))); 
        
        $moip->validate('Identification');        
    
        try
        {
            $answer = $moip->send();
        
            if($error = $answer->error)
            {
                $result->setFailed($error);
                throw new Am_Exception_InputError("Moip Pyment Plugin Error: ".$error);        
            }
            
            $xml = simplexml_load_string($answer->xml);            
            $token = (string) $xml->Resposta->Token;
            $status = (string) $xml->Resposta->Status;
            
            if($status != 'Sucesso')
            {
                throw new Am_Exception_IntputError("Moip Payment Plugin Error: returned status is not sucesso");
            }
            
            $invoice->data()->set(Am_Paysystem_Moip::TOKEN, $token)->update(); 
        }
        catch(Exception $e)
        {
            $this->getDi()->errorLogTable->logException($e);
        }
    }
    
    public function _initSetupForm(Am_Form_Setup $form)
    {
        $form->addText('key', array('size' => '40', 'maxlen' => '40'))
        ->setLabel('Key for authorization: ')
        ->addRule('required');

        $form->addText('token', array('size' => '32', 'maxlen' => '32'))
        ->setLabel('Token for authorization: ')
        ->addRule('required');

        $form->addAdvCheckbox("testing")->setLabel("Test Mode Enabled");
    }

    function getReadme()
    {
        return <<<CUT
<b>Moip Payment Plugin Configuration</b>
CUT;
    }

    public function createTransaction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs)
    {
        return new Am_Paysystem_Transaction_Moip($this, $request, $response, $invokeArgs);
    }
}

class Am_Paysystem_Transaction_Moip  extends Am_Paysystem_Transaction_Incoming
{
    public function getUniqId()
    {

    }
    public function findInvoiceId()
    {

    }

    public function validateStatus()
    {

    }

    public function validateTerms()
    {
         
    }

    public function validateSource()
    {

    }
}

class Am_Paysystem_Transaction_MoipSail extends Am_Paysystem_Transaction_CreditCard
{
    public function validate()
    {

    }

    public function parseResponse()
    {

    }

    public function getUniqId()
    {
         
    }
}
